package com.yl.chainStore.interceptor

import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *进行权限判断的拦截器
 */
class UserPowerInterceptor : HandlerInterceptor {
	companion object {
		private val log = LoggerFactory.getLogger(UserPowerInterceptor::class.java)
	}

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService


	override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
		log.info("admin用户 这里是前端访问的接口url=========={}", request.requestURL)
		val cacheUser = iCompanyUserService.getCacheUser(getContext().companyId, getContext().userId)
		if(cacheUser == null){
			response.contentType = "text/html;charset=utf-8"
			response.writer.println("{\"code\":307,\"msg\":\"游客没有权限访问接口，请联系管理员授权\"}")
			return false
		}
		// TODO: 2021/11/5 后面删掉
		if (cacheUser.userCode == "admin") {
			return true
		}
		if(1==1){
			return true
		}
		//从这里开始已经可以拿到webContext内的数据了
		if (handler is HandlerMethod) {
			try {
				val methodAnnotation: PermsCode? = handler.getMethodAnnotation(PermsCode::class.java)
				if (methodAnnotation != null) {
					val permsCode: String = methodAnnotation.value
					if (permsCode.isNotEmpty()) {
						if (!iCompanyUserService.havePermCode(
								getContext().companyId, getContext().userId, permsCode,
								getContext().subCompanyId
							)
						) {
							response.contentType = "text/html;charset=utf-8"
							response.writer.println("{\"code\":314,\"msg\":\"没有权限访问接口，请联系管理员授权\"}")
							return false
						}
					}
				}
			} catch (e: Exception) {
				e.printStackTrace()
				response.contentType = "text/html;charset=utf-8"
				response.writer.println("{\"code\":314,\"msg\":\"没有权限访问接口，请联系管理员授权\"}")
				return false
			}
		}
		log.info("这里是前端访问的接口url=========={}", request.requestURL)
		return true
	}

}
